<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyBnInvoiceListDetailTable;
use App\Http\Models\Mysql\SsyBnInvoiceListTable;
use App\Http\Repository\BanniuRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class pullBnInvoice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pullBnInvoice {--start=} {--end=} {--sourceId=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '拉取班牛发票数据';

    /**
     * Create a new command instance.
     * 0 /1 * * *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $autoKey = "auto_pullBnInvoice";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $start = $this->option("start") ?? "";
        $end = $this->option("end") ?? "";
        $sourceId = $this->option("sourceId") ?? "";
        if(empty($sourceId)){//没有指定订单号，默认近1小时的修改数据
            $start = date("Y-m-d H:i:s", strtotime("- 1 hour"));
            $end = date("Y-m-d H:i:s");
        }
        $totalPage = 1;
        $limit = 200;
        for($page = 1; $page <= $totalPage; $page++){
            $list = BanniuRepository::list(['star_modified' => $start, 'end_modified' => $end, 'sourceId' => $sourceId], $page, $limit);
            $page == 1 && $totalPage = $list['response']['map']['total_page_num'] ?? 0;
            $this->saveData($list, $page, $totalPage);
        }
        Cache::forget($autoKey);
    }

    //处理班牛数据入库
    public function saveData($data, $page, $totalPage)
    {
        $list = $data['response']['map']['result'] ?? [];
        $num = 1;
        if(empty($list)){
            echo "未获取到订单数据";
        }
        foreach ($list as $val) {
            if(!isset($val['819'])){
                echo "检测到{$totalPage}页，正在爬取，第{$page}页，处理：第{$num} 订单号：未发现";
                continue;
            }
            echo "检测到{$totalPage}页，正在爬取，第{$page}页，处理：第{$num} 订单号：{$val['819']}";
            $num++;
            if(!isset($val['-1'])){
                continue;
            }
            $payAmount = isset($val['5299']) && !empty($val['5299']) ? $val['5299'] :
                (isset($val['5300']) && !empty($val['5300']) ? $val['5300'] :
                    (isset($val['832']) && !empty($val['832']) ? $val['832'] : 0)
                );
            $save = [
                "pay_amount" => $payAmount,
                "taskid" => $val['-1'] ?? "",
                "adduserid" => $val['1'] ?? "",
                "douserid" => $val['2'] ?? "",
                "addtime" => $val['3'] ?? "",
                "updatetime" => $val['4'] ?? "",
                "status" => $val['5'] ?? "",
                "order_status" => $val['6'] ?? "",
                "sellerid" => $val['818'] ?? "",
                "sourceid" => $val['819'] ?? "",
                "buyername" => $val['820'] ?? "",
                "email" => $val['821'] ?? "",
                "invoice_headerid" => $val['792'] ?? "",
                "invoice_header" => $val['793'] ?? "",
                "invoicing_number" => $val['794'] ?? "",
                "order_detail" => isset($val['797']) ? serialize(json_decode($val['797'], true)) : "",
                "notes" => $val['831'] ?? "",
                "createtime" => date("Y-m-d H:i:s"),
                "order_title" => $val['1209'] ?? ""
            ];
            //查询是否已存在
            $exist = (new SsyBnInvoiceListTable())->where('sourceid', $val['819'])->first();
            if (!empty($exist)) {
                $res = (new SsyBnInvoiceListTable())->updateData($exist->id, $save);
                if($res['code'] === 0){
                    echo " 更新 success\n";
                }else{
                    echo " 更新 error\n";
                }
            } else {
                $res = (new SsyBnInvoiceListTable())->createData($save);
                if($res['code'] === 0){
                    echo " 创建 success\n";
                }else{
                    echo " 创建 error\n";
                }
            }
            //子订单数据，重新入库
            $detail = json_decode($val['797'] ?? "", true) ?: [];
            if (!empty($detail)) {
                (new SsyBnInvoiceListDetailTable())->deleteDataWhere(['sourceid' => $val['819']]);
            }
            foreach ($detail as $v) {
                $saveDetail = [
                    'son_order_no' => $v['798']  ?? "",//子订单号
                    'product_name' => $v['799'] ?? "",//商品标题
                    'product_id' => $v['800'] ?? "",//商品ID
                    'num' => $v['801'] ?? "",//购买数量
                    'price' => $v['802'] ?? "",//商品单价
                    'sku_title' => $v['803'] ?? "",//SKU属性
                    'sku_id' => $v['804'] ?? "",//SKUID
                    'sku_code' => $v['805'] ?? "",//商家编码
                    'refund_id' => $v['806'] ?? "",//退款ID
                    'shipping_express' => $v['808'] ?? "",//发货快递
                    'waybill_number' => $v['809'] ?? "",//运单号
                    'pay_amount' => $v['810'] ?? "",//实付金额
                    'return_order_number' => $v['811'] ?? "",//退货单号
                    'return_logistics_company' => $v['812'] ?? "",//退货物流公司
                    'reason_refund' => $v['813'] ?? "",//退款原因
                    'product_code' => $v['814'] ?? "",//货品编号
                    'logistics_company' => $v['815'] ?? "",//物流公司
                    'refund_time' => $v['816'] ?? "",//退款申请时间
                    'refund_amount' => $v['817'] ?? "",//退款金额
                    'createtime' => date("Y-m-d H:i:s"),
                    'sourceid' => $val['819'] ?? "",
                    'taskid' => $val['-1'] ?? ""
                ];
                (new SsyBnInvoiceListDetailTable())->createData($saveDetail);
            }
        }
    }
}
